import asyncio
from config import CONFIG
import asyncio
import websockets
from cozepy import Coze, TokenAuth, Message, COZE_CN_BASE_URL
import json
from config import CONFIG 

async def call_coze_workflow(workflow_id: str, input_text: str):
    """改进后的工作流调用函数"""
    try:
        coze = Coze(
            auth=TokenAuth(token=CONFIG["api_token"]),
            base_url=COZE_CN_BASE_URL
        )
        message = Message.build_user_question_text(input_text)
        
        loop = asyncio.get_running_loop()
        response = await loop.run_in_executor(
            None,
            lambda: coze.workflows.runs.create(
                workflow_id=workflow_id,
                parameters={'input': message.content}
            )
        )
        
        # 调试输出原始响应
        print("\n[原始响应] 工作流返回数据:")
        print(f"数据类型: {type(response.data)}")
        print(f"原始内容: {response.data}")

        # 新版响应处理逻辑
        processed_data = {}
        if isinstance(response.data, dict):
            processed_data = response.data
        elif isinstance(response.data, str):
            try:
                processed_data = json.loads(response.data)
            except json.JSONDecodeError:
                processed_data = {"output": response.data}  # 原始字符串包装成字典
        else:
            processed_data = {"raw_data": str(response.data)}

        return {
            "status": "success",
            "data": processed_data,
            "error": None
        }

    except Exception as e:
        print(f"API调用异常: {str(e)}")
        return {
            "status": "error",
            "data": None,
            "error": str(e)
        }


async def create_conversation(session):
    """创建会话"""
    url = 'https://api.coze.cn/v1/conversation/create'
    headers = {
        "Authorization": f"Bearer {CONFIG['api_token']}",
        "Content-Type": "application/json"
    }
    
    data = {
        "bot_id": CONFIG["bot2_id"]
    }
    
    print(f"[调试] 创建会话请求数据: {data}")
    async with session.post(url, headers=headers, json=data) as response:
        result = await response.json()
        print(f"[调试] 创建会话响应: {result}")
        if 'code' in result and result['code'] == 0:
            return result['data']['id']
        raise Exception(f"创建会话失败: {result}")

async def create_message(session, conversation_id, content):
    """创建消息"""
    url = f'https://api.coze.cn/v1/conversation/message/create'
    headers = {
        "Authorization": f"Bearer {CONFIG['api_token']}",
        "Content-Type": "application/json"
    }
    
    params = {
        "conversation_id": conversation_id
    }
    
    data = {
        "role": "user",
        "content": content,
        "content_type": "text"
    }
    
    print(f"[调试] 创建消息请求数据: {data}")
    print(f"[调试] 会话ID: {conversation_id}")
    
    async with session.post(url, headers=headers, params=params, json=data) as response:
        result = await response.json()
        print(f"[调试] 创建消息响应: {result}")
        if 'code' in result and result['code'] == 0:
            return result['data']['id']
        raise Exception(f"创建消息失败: {result}")

async def create_chat(session, conversation_id,  user_id):
    """发起对话"""
    url = 'https://api.coze.cn/v3/chat'
    headers = {
        "Authorization": f"Bearer {CONFIG['api_token']}",
        "Content-Type": "application/json"
    }
    data = {
        "bot_id": CONFIG["bot2_id"],
        "user_id":user_id,
        "auto_save_history": True
    }
    params = {
        "conversation_id": conversation_id
    }
    
    print(f"[调试] 创建对话请求数据: {data}")
    print(f"[调试] 使用会话ID: {conversation_id}")
    
    async with session.post(url, headers=headers, params=params, json=data) as response:
        result = await response.json()
        print(f"[调试] 创建对话响应: {result}")
        if 'code' in result and result['code'] == 0:
            return result['data']['id']
        raise Exception(f"创建对话失败: {result}")


'''
BUG!!!!!!!
【【【这里总是会自己捏造一个conversation_id，不知道为啥，coze官网试了一下正常运作不会这样的，
get_chat_result可以先用一个固定的chat占位测试】】】

占位信息：
 params = {
        "conversation_id": 7469685690054426635,
        "chat_id": 7470851613004169256
    }

具体问题：
[调试] 创建对话响应: {'data': {'id': '7470756054243000371', 
'conversation_id': '7470756054242983987', 
'bot_id': '7469592638715625526', 
'created_at': 1739420942, 'last_error': {'code': 0, 'msg': ''}, 
'status': 'in_progress'}, 'code': 0, 'msg': ''}
[发起对话] ID: 7470756054243000371
[调试] 获取对话结果请求参数: {'conversation_id': '7470756038975897640', 
'chat_id': '7470756054243000371'}
'''


async def get_chat_result(session, conversation_id, chat_id):
    """获取对话结果"""
    url = 'https://api.coze.cn/v3/chat/message/list'
    headers = {
        "Authorization": f"Bearer {CONFIG['api_token']}",
        "Content-Type": "application/json"
    }
    
    params = {
        "conversation_id": conversation_id,
        "chat_id": chat_id
    }
    
    print(f"[调试] 获取对话结果请求参数: {params}")
    
    max_retries = 30  # 增加重试次数，因为每5秒检查一次
    for i in range(max_retries):
        async with session.get(url, headers=headers, params=params) as response:
            result = await response.json()
            print(f"[调试] 获取对话结果响应 (第{i+1}次): {result}")
            
            if 'code' in result and result['code'] == 0:
                # 检查状态  
                status = result.get('data', {}).get('status', '')
 
                if status != 'completed':
                    print(f"[状态] 对话仍在进行中 (status: {status})，等待5秒后重试...")
                    await asyncio.sleep(5)
                    continue
                
                
                # 状态为completed时处理消息
                messages = result['data'].get('messages', [])
                for msg in reversed(messages):
                    if msg['role'] == 'assistant' and msg['type'] == 'answer':
                        return msg
                raise Exception("未找到助手的回复")
                
            await asyncio.sleep(1)
    raise Exception("获取对话结果超时")
